import { DataGridHeaderCell, UseFilterHistory } from "./types";

export function useFilterHistory(): UseFilterHistory {

    const maxColumnFilterCount = 5;

    function getHeaderCellKey(headerCell: DataGridHeaderCell): string {
        return headerCell.field;
    }

    function getFilterHistory(headerCell: DataGridHeaderCell): any[] {
        const headerCellKey = getHeaderCellKey(headerCell);
        const filterHistoryString = localStorage.getItem(headerCellKey);
        const filterHistroy = filterHistoryString ? JSON.parse(filterHistoryString) as any[] : [];
        return filterHistroy;
    }

    function setFilterHistory(headerCell: DataGridHeaderCell, filterHistory: any[]) {
        const headerCellKey = getHeaderCellKey(headerCell);
        localStorage.setItem(headerCellKey, JSON.stringify(filterHistory));
    }

    function updateFilterHistory(headerCell: DataGridHeaderCell, filterString: string) {
        if (!filterString) {
            return;
        }
        const filterHistory = getFilterHistory(headerCell);
        const filterObject = filterHistory
            .find((item: any) => item.name === filterString) || { id: Date.now(), name: filterString, selectable: true };
        const latestFilterHistory = [filterObject, ...filterHistory.filter((item: any) => item.name !== filterString)];
        if (latestFilterHistory.length > maxColumnFilterCount) {
            latestFilterHistory.length = maxColumnFilterCount;
        }
        setFilterHistory(headerCell, latestFilterHistory);
    }

    function removeFilterHistory(headerCell: DataGridHeaderCell, filterString: string) {
        const filterHistory = getFilterHistory(headerCell);
        const latestFilterHistory = [...filterHistory.filter((item: any) => item.name !== filterString)];
        const headerCellKey = getHeaderCellKey(headerCell);
        localStorage.setItem(headerCellKey, JSON.stringify(latestFilterHistory));
    }

    return { getFilterHistory, removeFilterHistory,setFilterHistory, updateFilterHistory };

}
